<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <title>CRM HTML Web Resource</title>
    <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <script src="../../ClientGlobalContext.js.aspx" type="text/javascript"></script>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="../script/DynaHx.js" type="text/javascript"></script>
</head>

<body>


    <!-- Vue 应用 -->
    <div id="app">
        <!-- 加载动画 -->
        <div v-if="loading">加载中...</div>
        {{ message }}
        <div v-if="dataObj">
            <p>id: {{ dataObj.id }}</p>
            <p>entityName: {{ dataObj.entityName }}</p>
        </div>
        <div v-if="arrayObj.length > 0">
            <h3>查询结果:</h3>
            <ul>
                <li v-for="item in arrayObj" :key="item.contactid">
                    {{ item.firstname }} - {{ item.mobilephone }}
                </li>
            </ul>
        </div>
    </div>


    <script>
        
        var xrm = window.parent.Xrm;
        var context = xrm.Utility.getPageContext();
        xrm.Utility.closeProgressIndicator();
        console.log("input", context.input);

        function getQueryParameter(paramName) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(paramName);
        }

        function queryContact(){
                // NOTE: retrieveMultipleRecords is available in online mode, if you need this functionality change the call to Xrm.WebApi.online.retrieveMultipleRecords
                // https://learn.microsoft.com/en-us/power-apps/developer/model-driven-apps/clientapi/reference/xrm-webapi/online
                Xrm.WebApi.retrieveMultipleRecords("contact", "?$select=firstname,mobilephone&$filter=mobilephone ne null&$orderby=createdon desc").then(
                    function success(results) {
                        debugger;
                        console.log(results);
                        for (var i = 0; i < results.entities.length; i++) {
                            var result = results.entities[i];
                            // Columns
                            var contactid = result["contactid"]; // Guid
                            var firstname = result["firstname"]; // Text
                            var mobilephone = result["mobilephone"]; // Text
                        }
                    },
                    function(error) {
                        console.log(error.message);
                    }
                );
        }

       async function  queryContactAsync(){
                // NOTE: retrieveMultipleRecords is available in online mode, if you need this functionality change the call to Xrm.WebApi.online.retrieveMultipleRecords
                // https://learn.microsoft.com/en-us/power-apps/developer/model-driven-apps/clientapi/reference/xrm-webapi/online
            try {
                
             let result =  await  Xrm.WebApi.retrieveMultipleRecords("contact", "?$select=firstname,mobilephone&$filter=mobilephone ne null&$orderby=createdon desc");
             return result;
            }catch (error) {
                console.error("查询联系人失败:", error);
                throw error; // 重新抛出错误以便在调用处处理
            }
        }

        // ...existing code...
        async function queryContactSafeAsync() {
            // 直接返回 entities，异常由调用方处理
            let result = await Xrm.WebApi.retrieveMultipleRecords(
                "contact",
                "?$select=firstname,mobilephone&$filter=mobilephone ne null&$orderby=createdon desc"
            );
            return result.entities || [];
        }
        // ...existing code...

        /**
         * 安全地等待一个 Promise，捕获异常并返回默认值
         * @param {Promise} promise - 要等待的 Promise
         * @param {*} fallback - 如果 Promise 失败，返回的默认值
         * @returns {Promise<*>} 返回一个 Promise，解析为结果或默认值
         */
        async function safeAwait(promise, fallback = null) {
            try {
                return await promise;
            } catch (error) {
                console.error('执行失败:', error);
                return fallback; // 返回默认值
            }
        }

        /**
         * 异步查询指定实体的记录
         * @param {string} entityLogicalName - 实体逻辑名称
         * @param {string} query - 查询字符串
         * @param {object} optionParams - 可选参数
         * @returns {Promise<Array>} 返回一个 Promise，解析为查询结果数组
         */
        function retrieveFromQueryAsync(entityLogicalName, query, optionParams = {}) {
            return new Promise((resolve, reject) => {
                DynaHx.Da.retrieveFromQuery(entityLogicalName, query, {
                    ...optionParams,
                    successCallback: function(result) { resolve((result && Array.isArray(result.data)) ? result.data : []); },
                    errorCallback: function(error) { reject(error); }
                });
            });
        }


        /*const data = getQueryParameter("data");
        console.log("传递的数据:", data);
        const dataObj = JSON.parse(data);
        if (dataObj && dataObj.hasOwnProperty('id') && dataObj.hasOwnProperty('entityName')) {
            let id = dataObj.id;
            let entityName = dataObj.entityName;
            console.log("id:", id);
            console.log("entityName:", entityName);
        } else {
            console.log("dataObj 不包含 id 或 entityName 属性");
        }*/

        const { createApp, ref, onMounted } = Vue;

        const app = createApp({
            setup() {
                const message = ref('Hello vue!');
                const loading = ref(true); // 初始化为 true，显示加载动画
                const dataObj = ref({
                    id: null,
                    entityName: null
                }); // 初始化为 null 
                const arrayObj = ref([]); // 初始化为一个空数组

                // 使用 onMounted 钩子
                onMounted(async() => {
                    //debugger
                    let data = getQueryParameter("data");
                    let dataRef = JSON.parse(data);
                    if (dataRef && dataRef.hasOwnProperty('id') && dataRef.hasOwnProperty('entityName')) {
                        let id = dataRef.id;
                        let entityName = dataRef.entityName;
                        console.log("id:", id);
                        console.log("entityName:", entityName);
                    } else {
                        console.log("dataObj 不包含 id 或 entityName 属性");
                    }
                    dataObj.value = dataRef
                    console.log('Vue 应用已挂载');
                    

                    //queryContact();

                    // queryContactAsync().then((results)=>{
                    //   debugger;
                    //   console.log(results);
                    //     for (var i = 0; i < results.entities.length; i++) {
                    //         var result = results.entities[i];
                    //         // Columns
                    //         var contactid = result["contactid"]; // Guid
                    //         var firstname = result["firstname"]; // Text
                    //         var mobilephone = result["mobilephone"]; // Text
                    //         arrayObj.value.push({
                    //             contactid: contactid,
                    //             firstname: firstname,
                    //             mobilephone: mobilephone
                    //         });
                    //     }

                    // }).catch((error)=>{
                    //     console.error("查询联系人失败:", error);
                    // });

            
                    

                     const entities = await safeAwait(queryContactSafeAsync(), []);
                
                        for (let i = 0; i < entities.length; i++) {
                            const result = entities[i];
                            arrayObj.value.push({
                                contactid: result["contactid"],
                                firstname: result["firstname"],
                                mobilephone: result["mobilephone"]
                            });
                        }


                  const result = await safeAwait(
                        retrieveFromQueryAsync("contact", "$select=firstname,mobilephone&$filter=mobilephone eq null&$orderby=createdon desc"),
                        []  // fallback 默认值
                    );

                    for (const index in result) {

                       //debugger;
                        const item = result[index];
                        arrayObj.value.push({
                            contactid: item.getString("contactid"),
                            firstname: item.getString("firstname"),
                            mobilephone: item.getString("mobilephone")
                        });
                    }

                    loading.value = false; // 挂载完成后隐藏加载动画

                });

                return {
                    message,
                    loading,
                    dataObj,
                    arrayObj
                };
            }
        });

        // 添加全局错误处理器
        app.config.errorHandler = (err, vm, info) => {
            console.error('捕获到错误:', err, info);
        };

        // 挂载应用
        app.mount('#app');

    </script>
</body>

</html>